import datetime
from database.common import cursor

def select_weibo_id(weibo_id):
    sql = """
    SELECT * FROM weibo_info WHERE weibo_id = %s
    """
    cursor.execute(sql, (weibo_id,))
    return cursor.fetchone()

def select_weibo_by_release_time(user_id, limited):
    sql = """
    SELECT * FROM weibo_info WHERE user_id = %s ORDER BY release_time DESC LIMIT %s
    """
    cursor.execute(sql, (user_id, limited))
    return cursor.fetchall()

def insert_weibo(weibo_class):

    sql = "INSERT INTO weibo_info (weibo_id, user_id, content, attitudes, comments, reposts, release_time, create_time, update_time) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    cursor.execute(sql, (weibo_class.weibo_id, weibo_class.user_id, weibo_class.content, 
                         weibo_class.attitudes, weibo_class.comments, weibo_class.reposts, 
                         weibo_class.release_time, now, now))
    
def update_weibo(weibo_class):

    sql = """
    UPDATE weibo_info SET
    attitudes = %s, comments = %s, reposts = %s
    where weibo_id = %s
    """
    
    params = (weibo_class.attitudes, weibo_class.comments, weibo_class.reposts, weibo_class.weibo_id)
    # complete_sql = cursor.mogrify(sql, params)  # 移除.decode('utf-8')
    # print("完整SQL:", complete_sql)
    
    cursor.execute(sql, params)


def count_activity_by_release_time(user_id, start_time, end_time):
    # 统计赞、评论、转发数量
    sql = """
    SELECT SUM(attitudes) AS likes, SUM(comments) AS comments, SUM(reposts) AS reposts FROM weibo_info WHERE user_id = %s AND release_time BETWEEN %s AND %s
    """
    params = (user_id, start_time, end_time)
    # complete_sql = cursor.mogrify(sql, params)  
    # print("完整SQL:", complete_sql)
    
    cursor.execute(sql, params)
    return cursor.fetchone()